package com.core.website.service.impl;

import com.core.website.common.Result;
import com.core.website.common.ResultUtil;
import com.core.website.entity.User;
import com.core.website.mapper.*;
import com.core.website.service.LoginService;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.core.website.api.LoginApi.heartbeatIpList;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private AccessMapper accessMapper;
    @Autowired
    private ConfigMapper configMapper;
    @Override
    public Result login(User user) {
        if(null==user){
            return ResultUtil.error(-1,"参数为空!");
        }
        if(StringUtil.isEmpty(user.getUserName())){
            return ResultUtil.error(-1,"用户名不能为空!");
        }
        if(StringUtil.isEmpty(user.getPassword())){
            return ResultUtil.error(-1,"密码不能为空!");
        }
        User userDO=loginMapper.findByUserName(user.getUserName());

        if(null==userDO|| StringUtils.isEmpty(userDO.getSalt())){
            return ResultUtil.error(-1,"找不到用户!");
        }
        if("stop".equals(userDO.getUserStatus())){
            return ResultUtil.error(-1,"用户已停用!");
        }
        Subject subject= SecurityUtils.getSubject();
        String newPs = new SimpleHash("MD5", user.getPassword(), userDO.getSalt(), 1024).toHex();
        AuthenticationToken token=new UsernamePasswordToken(user.getUserName(),newPs);
        try {
            subject.login(token);
            subject.getSession().setTimeout(1800000);
            Set<String> list = roleMapper.queryRoleCodeByUserId(userDO.getId());
            return ResultUtil.success(list);
        } catch (IncorrectCredentialsException ice){
            log.error(ice.getMessage());
            return ResultUtil.error(-1,"密码验证失败！");
        }catch(UnknownAccountException uae){
            log.error(uae.getMessage());
            return ResultUtil.error(-1,"找不到用户!");
        }catch(LockedAccountException lae){
            log.error(lae.getMessage());
            return ResultUtil.error(-1,"账户已锁定！");
        }catch(ExcessiveAttemptsException eae){
            log.error(eae.getMessage());
            return ResultUtil.error(-1,"用户名或密码错误次数太多！");
        }catch(AuthenticationException ae){
            log.error(ae.getMessage());
            ae.printStackTrace();
            return ResultUtil.error(-1,"验证未通过！");
        }catch (Exception e) {
            log.error(e.getMessage());
            return ResultUtil.error(-1,"验证未通过！");
        }
    }

    @Override
    public Map<String, Object> activityStatistical() {
        int olLineNum = heartbeatIpList.keySet().size();
        int todayNum=contentMapper.queryTodayNum();
        int totalNum=contentMapper.queryTotalNum();
        int todayAccess=accessMapper.queryDayAccess();
        int totalAccess=accessMapper.queryTotalAccess()+todayAccess;
        Map<String,Object> result=new HashMap<>();
        result.put("olLineNum",olLineNum);
        result.put("todayNum",todayNum);
        result.put("totalNum",totalNum);
        result.put("todayAccess",todayAccess);
        result.put("totalAccess",totalAccess);
        return result;
    }

    @Override
    public String getConfig(String key) {
        return configMapper.getConfig(key);
    }

    @Override
    public void setConfig(String key, String value) {
        configMapper.delByKey(key);
        configMapper.setConfig(key,value);
    }
}
